﻿module Sustainalytics.Authentication {

    export var authenticationHttpInterceptorName = 'AuthenticationHttpInterceptor';

    angular.module(authenticationModuleName).factory(authenticationHttpInterceptorName, function (

        $rootScope: RootScope,
        $q: ng.IQService,
        $location: ng.ILocaleService,
        staticObjects: IStaticObjects) {

        return {
            request: (config: ng.IRequestConfig) => {

                config.headers = config.headers || {};

                if ($rootScope.authData && $rootScope.authData.access_token) {
                    config.headers.Authorization = 'Bearer ' + $rootScope.authData.access_token;
                }

                return config;
            },

            response: (response) => {

                //Commented because accessing a Web API that yield HTTP Status 401 does not necessarily mean that the whole feature is not available
                //if (response.status === 401) {
                //    // handle the case where the user is not authenticated
                //    staticObjects.clearUserInfo();
                //    if ($location.url() != '/login') {
                //        $location.url('/login');
                //    }
                //}

                return response || $q.when(response);
            }
        }
    });
} 